package com.wzx.data.serviceimpl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzx.basics.baseVo.Result;
import com.wzx.basics.exception.WzxException;
import com.wzx.basics.utils.ResultUtil;
import com.wzx.data.dao.mapper.TeacherMapper;
import com.wzx.data.entity.Role;
import com.wzx.data.entity.Teacher;
import com.wzx.data.entity.User;
import com.wzx.data.entity.UserRole;
import com.wzx.data.service.IRoleService;
import com.wzx.data.service.ITeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzx.data.service.IUserRoleService;
import com.wzx.data.service.IUserService;
import com.wzx.data.vo.TeacherVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 教师 服务层接口实现
 * @author wzx
 * @since 2023/03/20
 */
@Slf4j
@Service
public class ITeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements ITeacherService {
    @Autowired
    private IUserService userService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IRoleService roleService;
    @Override
    public Result saveTeacher(TeacherVo vo) {
        //封装user对象
        User user = buildUser(vo);
        //查看是否存在用户
        QueryWrapper<User> userQw = new QueryWrapper<>();
        userQw.and(wrapper -> wrapper.eq("username", user.getUsername()).or().eq("mobile",user.getMobile()));
        if(userService.count(userQw) > 0L) {
            return ResultUtil.error("登陆账号/手机号重复");
        }
        String encryptPass = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(encryptPass).setType(1);
        userService.saveOrUpdate(user);

        User one = userService.getOne(userQw);
        //获取已插入的用户id并设置教师Id
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(vo,teacher);
        teacher.setId(one.getId());
        this.save(teacher);
        this.addRole(user);
        return ResultUtil.success();
    }

    @Override
    public Result updateTeacher(TeacherVo vo) {
        Teacher teacher = new Teacher();
        BeanUtils.copyProperties(vo,teacher);
        this.updateById(teacher);
        return ResultUtil.success();
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTeacher(String id) {
        //获取用户角色关联信息
        LambdaQueryWrapper<UserRole> lambda  =new LambdaQueryWrapper<UserRole>();
        lambda.eq(UserRole::getUserId,id);
        userRoleService.remove(lambda);
        //删除用户信息和教师信息
        this.removeById(id);
        userService.removeById(id);
    }

    /**
     * 封装User
     * @param vo
     * @return
     */
    private User buildUser(TeacherVo vo) {
        User user = new User();
        if(ObjectUtil.isNotNull(vo.getUsername())){
            user.setUsername(vo.getUsername());
        }
        if(ObjectUtil.isNotNull(vo.getPassword())){
            user.setPassword(vo.getPassword());
        }
        if(ObjectUtil.isNotNull(vo.getAvatar())){
            user.setAvatar(vo.getAvatar());
        }
        if(ObjectUtil.isNotNull(vo.getAge())){
            user.setAge(vo.getAge());
        }
        if(ObjectUtil.isNotNull(vo.getEmail())){
            user.setEmail(vo.getEmail());
        }
        if(ObjectUtil.isNotNull(vo.getMobile())){
            user.setMobile(vo.getMobile());
        }
        if(ObjectUtil.isNotNull(vo.getSex())){
            user.setSex(vo.getSex());
        }
        if(ObjectUtil.isNotNull(vo.getRemark())){
            user.setDescription(vo.getRemark());
        }
        if(ObjectUtil.isNotNull(vo.getName())){
            user.setNickname(vo.getName());
        }
        return user;
    }
    /**
     * 添加角色
     */
    private void addRole(User user){
        LambdaQueryWrapper<User> lambda = new LambdaQueryWrapper<User>();
        lambda.eq(User::getUsername, user.getUsername());
        User one = userService.getOne(lambda);
        if(one==null){
            throw new WzxException("查无该角色");
        }
        LambdaQueryWrapper<Role> roleLambda = new LambdaQueryWrapper<Role>();
        roleLambda.eq(Role::getName,"ROLE_TEACHER");
        Role role = roleService.getOne(roleLambda);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(role.getId());
        userRoleService.save(userRole);
    }
}